# -*- coding: utf-8 -*-
"""
Created on Mon Apr 27 15:54:00 2020

@author: Farman
"""

import pathlib
import os
import sys


def list_dir(abs_path='.'):
    '''
    List all files and directories in path 'in_path',
    save file names to a file with name 'save_to_file'.

    Parameters
    ----------
    in_path : string
        Full path of files and directories to be list.

    Returns
    -------
    None.
    '''
    working_dir = pathlib.PurePath(abs_path)
    print('Searching ...', working_dir)
    
    files = os.listdir(working_dir)
    #print('files', files)
    
    file_name_list = []
    dir_name_list = []
    
    for file in files:
        #print(working_dir / file)
        
        # escape NTFS system directory
        if sys.platform == 'win32' and file.find('System Volume Information') > -1:
            continue
        
        file = working_dir / file
        
        if os.path.isdir(file):
            list_dir(file)
            dir_name_list.append(file)
        else:
            file_name_list.append(file)
    
    file_name = str(working_dir)
    file_name = file_name.replace('\\', '_')
    file_name = file_name.replace('/', '_')
    file_name = file_name.replace(':', '=')
    #print('Working dir', file_name)
    file_name += '.txt'
    
    file_name_list = [str(file) + '\n' for file in file_name_list]
    dir_name_list  = [str(file) + '\n' for file in dir_name_list]
    
    with open(file_name, 'w') as f:
        if len(dir_name_list):
            f.write('Directories in [%s]\n'%working_dir)
            f.write('='*40 + '\n')
            f.writelines(dir_name_list)
        
        if len(file_name_list):
            f.write('\nFiles in [%s]\n'%working_dir)
            f.write('='*40 + '\n')
            f.writelines(file_name_list)
        
    return



if __name__ == '__main__':
    print('Files and directories lister.')
    print('=' * 40)
    
    if len(sys.argv) > 1:
        list_dir(sys.argv[1])
    else:
        list_dir('.')
        
    print('Job done.')